import { useState, useEffect } from 'react';
import { Descriptions, Avatar, Card, Tag, message, Spin } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import axios from 'axios';
import { getAuthToken } from "@/router/index.jsx";

const formatBytes = (bytes) => {
  if (!bytes && bytes !== 0) return '--';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

export default function Profile() {
  const [userInfo, setUserInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    const loadData = async () => {
      try {
        // 获取存储的 token
        const token = getAuthToken();
        if (!token) {
          message.error('未检测到登录信息，请重新登录');
          setError(true);
          return;
        }

        // 直接使用axios发送请求
        const response = await axios.get(
            'http://localhost:8080/api/user/info',
            {
              headers: {
                Authorization: `${token}`
              }
            }
        );

        // 检查响应状态码
        if (response.data.code !== 200) {
          throw new Error(response.data.message || '获取用户信息失败');
        }

        // 设置用户信息数据
        setUserInfo(response.data.data);
      } catch (error) {
        console.error('用户信息加载失败:', error);
        message.error(error.message || '用户信息加载失败');
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  if (loading) {
    return (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" tip="加载用户信息中..." />
        </div>
    );
  }

  if (error || !userInfo) {
    return <div style={{ textAlign: 'center', padding: '50px' }}>数据加载失败，请检查登录状态</div>;
  }

  return (
      <Card title="个人资料" bordered={false}>
        <div className="avatar-section" style={{ textAlign: 'center', marginBottom: 24 }}>
          <Avatar
              size={128}
              icon={<UserOutlined />}
              style={{ backgroundColor: '#1890ff' }}
          />
        </div>

        <Descriptions column={1} bordered>
          <Descriptions.Item label="用户ID">{userInfo.id || '--'}</Descriptions.Item>
          <Descriptions.Item label="用户名">{userInfo.username || '--'}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{userInfo.email || '未绑定'}</Descriptions.Item>
          <Descriptions.Item label="用户角色">
            <Tag color="blue">{userInfo.userRole || '--'}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="用户等级">
            <Tag color="gold">LV{userInfo.userLevel ?? '--'}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="魔力值">{userInfo.magicValue ?? 0}</Descriptions.Item>
          <Descriptions.Item label="上传总量">
            {formatBytes(userInfo.uploadAmount)}
          </Descriptions.Item>
          <Descriptions.Item label="下载总量">
            {formatBytes(userInfo.downloadAmount)}
          </Descriptions.Item>
          <Descriptions.Item label="分享率">
          <span style={{ color: (userInfo.shareRatio || 0) >= 1 ? '#52c41a' : '#f5222d' }}>
            {userInfo.shareRatio ? userInfo.shareRatio.toFixed(2) : '--'}
          </span>
          </Descriptions.Item>
          <Descriptions.Item label="做种数量">{userInfo.seedCount ?? 0}</Descriptions.Item>
          <Descriptions.Item label="做种时长">{userInfo.seedDuration ?? 0}小时</Descriptions.Item>
          <Descriptions.Item label="最后登录时间">
            {userInfo.lastLoginTime ? new Date(userInfo.lastLoginTime).toLocaleString() : '--'}
          </Descriptions.Item>
          <Descriptions.Item label="账户状态">
            <Tag color={userInfo.status === 'active' ? 'green' : 'red'}>
              {userInfo.status === 'active' ? '正常' : '禁用'}
            </Tag>
          </Descriptions.Item>
        </Descriptions>
      </Card>
  );
}